package cn.xiaolang.thread.threadpool;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

@Slf4j
public class ThreadPoolExecutorStarted {


    public static void main(String[] args) {

        /**
         *  <p>初始线程池大小 5 + 队列大小 3 + 加到线程池最大10 = 共13个任务</p>
         *  <p>其他任务被 ThreadPoolExecutor.DiscardPolicy() 拒绝策略</p>
         * @param args
         */

        String threadNameFormat = "juc-pool-thread-%d";

        /**
         * corePoolSize推荐设置为：可用core*2
         * Runtime.getRuntime().availableProcessors()*2
         */
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                5,
                10,
                0L,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(3),
                new ThreadFactoryBuilder().setNameFormat(threadNameFormat).build(),
                // 静默忽略拒绝
                new ThreadPoolExecutor.DiscardPolicy());

        CountDownLatch countDownLatch = new CountDownLatch(13);


        for (int i = 0; i < 50; i++) {
            log.info("添加任务{}", i);
            threadPoolExecutor.execute(() -> {
                log.info("active:{},poolSize:{},queueSize:{}"
                        , threadPoolExecutor.getActiveCount()
                        , threadPoolExecutor.getPoolSize()
                        , threadPoolExecutor.getQueue().size());
                try {
                    Thread.sleep(1000 * 10);
                } catch (InterruptedException e) {
                    log.error("", e);
                } finally {
                    countDownLatch.countDown();
                }
            });
        }

        try {
            threadPoolExecutor.shutdown();
            countDownLatch.await();
            log.info("all thread execute over!");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

